<?php
/**
 * @package Admin
 * @author Henrique Droog <henridroog@gmail.com>
 * @name ModuleMapper
 * @since 19/03/2011
 * @version 1.0
 */
class Admin_Model_ModuleMapper {

    protected $_dbTable;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Admin_Model_DbTable_Module');
        }
        return $this->_dbTable;
    }

    public function save(Admin_Model_Module $module) {
        $data = array(
            'module_name' => $module->getName(),
        );
//        if ($module->getId()<=0)
//                $module->setId ("NULL");
        //if (null === ($id = $module->getId())) {
        if ($module->getId()<=0) {
            unset($data['module_id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('module_id = ?' => $module->getId()));
        }
    }

    public function find($id, Admin_Model_Module $module) {
        $result = $this->getDbTable()->find($id['id']);

        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $module->setId($row->module_id)
                  ->setName($row->module_name);
        return $module;
    }

    public function fetchAll() {
        $resultSet = $this->getDbTable()->fetchAll();
        
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Admin_Model_Role();
            $entry->setId($row->module_id)
                    ->setName($row->module_name);
            $entries[] = $entry;
        }
        return $entries;
    }
    //
    public function del(Admin_Model_Module $module){
        $where = array("module_id = ?" =>$module->getId());
        $resultSet = $this->getDbTable()->delete($where);
        return $resultSet;
    }

}